package com.gin.kotlin.no_gay_alliance.utils

import android.graphics.Bitmap
import android.graphics.Color
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.nio.charset.Charset
import java.security.MessageDigest


/**
 * 反色处理
 */
class InvertColorsTransformation : BitmapTransformation() {
    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        val width = toTransform.width
        val height = toTransform.height
        val result = pool[width, height, Bitmap.Config.ARGB_8888]

        for (y in 0 until height) {
            for (x in 0 until width) {
                val pixel = toTransform.getPixel(x, y)
                if (pixel != Color.TRANSPARENT) {
                    val alpha = Color.alpha(pixel)
                    val red = 255 - Color.red(pixel)
                    val green = 255 - Color.green(pixel)
                    val blue = 255 - Color.blue(pixel)
                    result.setPixel(x, y, Color.argb(alpha, red, green, blue))
                } else {
                    result.setPixel(x, y, Color.TRANSPARENT)
                }
            }
        }

        return result
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }

    companion object {
        private const val ID = "com.gin.kotlin.no_gay_alliance.utils.InvertColorsTransformation";
        private val ID_BYTES = ID.toByteArray(Charset.forName("UTF-8"));
    }
}